package com.googlecode.iiddefecttracker.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.googlecode.iiddefecttracker.domain.Project;
import com.googlecode.iiddefecttracker.service.ProjectService;

/**
 * I am a {@link SimpleFormController} for {@link Project}s.
 */
public class ProjectFormController extends SimpleFormController {
    
    private final ProjectService projectService;
    
    public ProjectFormController(final ProjectService projectService) {
        this.projectService = projectService;
    }
    
    @Override
    protected Object formBackingObject(final HttpServletRequest request)
            throws Exception {
        return super.formBackingObject(request);
    }
    
    @Override
    protected void initBinder(final HttpServletRequest request,
            final ServletRequestDataBinder binder) throws Exception {
        super.initBinder(request, binder);
        
        final SimpleDateFormat dateFormat = new SimpleDateFormat(
                "EEE, MMM d, ''yy", request.getLocale());
        dateFormat.setLenient(false);
        
        final String allFieldsOfDateType = null;
        binder.registerCustomEditor(Date.class, allFieldsOfDateType,
                new CustomDateEditor(dateFormat, true));
    }
    
    @Override
    protected ModelAndView onSubmit(final Object command) throws Exception {
        
        final Project project = (Project) command;
        
        projectService.saveProject(project);
        
        return new ModelAndView(new RedirectView(getSuccessView()));
    }
}
